<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\api\common\Program;
use app\common\library\Upload;
use app\common\model\ChatRoom;
use app\common\model\User as UserModel;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;


class User extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 用户信息
     * @ApiMethod (POST)
     * @path api/user/info
     */
    public function info()
    {
        $user_id = $this->auth->user_id;
        $info = UserModel::user_info($user_id);
        $this->success('请求成功',$info);
    }

    /**
     * 选择身份
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     * @path api/user/chooseIdentity
     */
    public function chooseIdentity()
    {
        $params = $this->request->param();
        $user_id = $this->auth->user_id;
        if (!$params['industry_id']) {
            $this->error(__('行业不能为空'));
        }
        if (!$params['company_typeid']) {
            $this->error(__('公司类型不能为空'));
        }
        if (!$params['position_id']) {
            $this->error(__('职位不能为空'));
        }
        if (!$params['province']) {
            $this->error(__('省名称不能为空'));
        }
        if (!$params['city']) {
            $this->error(__('市名称不能为空'));
        }
        $user = UserModel::where("user_id",$user_id)->find();
        $user->industry_id = $params["industry_id"];
        $user->company_typeid = $params["company_typeid"];
        $user->position_id = $params["position_id"];
        $user->province = $params["province"];
        $user->city = $params["city"];
        if(!$user->identification){
            $identification = Random::alnum(16).'_'.$user_id;
            $user_token = ChatRoom::getUserToken($identification);
            $user->identification = $identification;
            $user->access_token = $user_token['data']['access_token'];
            $user->uuid = $user_token['data']['user']['uuid'];
        }
        $user->save();
        $this->success("选择成功");
    }

    /**
     * 搜索历史
     * @ApiMethod (POST)
     * @path api/user/searchHistory
     */
    public function searchHistory()
    {
        $user_id = $this->auth->user_id;
        $where = "user_id = {$user_id}";
        $field = "id,name";
        $order = "add_time DESC";
        $list = Db::name("search_history")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /**
     * 删除搜索历史
     * @ApiMethod (POST)
     * @path api/user/delSearchHistory
     */
    public function delSearchHistory()
    {
        $user_id = $this->auth->user_id;
        $search_id = $this->request->post('search_id');
        $where = "user_id = {$user_id}";
        if($search_id){
            $where.= " AND id = {$search_id}";
        }
        Db::name("search_history")->where($where)->delete();
        $this->success("删除成功");
    }

    /**
     * 修改用户信息
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @path api/user/profile
     */
    public function profile()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $image = $this->request->post('image', '', 'trim,strip_tags,htmlspecialchars');
        $background_image = $this->request->post('background_image', '', 'trim,strip_tags,htmlspecialchars');
        $province = $this->request->post('province');
        $city = $this->request->post('city');
        if ($username) {
            $where = "username = '{$username}' AND user_id <> {$user_id} AND (logout = '0' OR logout = '3')";
            $exists = UserModel::where($where)->find();
            if ($exists) {
                $this->error(__('用户名已存在'));
            }
            if(is_mobile($username)){
                $this->error("用户名不能是手机号");
            }
            if(containsPhoneNumber($username)){
                $this->error("用户名不能是手机号");
            }
            $words = Db::name("sensitivewords")->where("name",trim(str_replace(' ', '', $username)))->find();
            if($words){
                $this->error("昵称存在敏感词,不允许修改");
            }
            if($user->open_id){
                $res = Program::TextRecognition($username,$user->open_id);
                if($res['code'] == 200 && $res['label'] != 100){
                    $this->error($res['data']);
                }elseif ($res['code'] == 201) {
                    $this->error($res['data']);
                }
            }
            $user->username = $username;
        }
        if($image){
            if($user->open_id){
                $res = Program::VideoRecognition(parse_url($image)["path"],2,$user->open_id);
                if($res['code'] == 200 && $res['label'] != 100){
                    $this->error($res['data']);
                }elseif ($res['code'] == 201) {
                    $this->error($res['data']);
                }
            }
            $user->image = parse_url($image)["path"];
        }
        if($background_image){
            if($user->open_id){
                $res = Program::VideoRecognition(parse_url($background_image)["path"],2,$user->open_id);
                if($res['code'] == 200 && $res['label'] != 100){
                    $this->error($res['data']);
                }elseif ($res['code'] == 201) {
                    $this->error($res['data']);
                }
            }
            $user->background_image = parse_url($background_image)["path"];
        }
        if($province){
            $user->province = $province;
        }
        if($city){
            $user->city = $city;
        }
        $user->save();
        $this->success("修改成功");
    }

    /**
     * 意见反馈
     * @path api/user/onlineMessage
     */
    public function onlineMessage()
    {
        $user_id = $this->auth->user_id;
        $content = $this->request->post('content');
        if (!$content){
            $this->error(__('反馈内容不能为空'));
        }
        $data = [
            "user_id"=>$user_id,
            "content"=>$content,
            "add_time"=>time(),
        ];
        $res = Db::name("advice")->insert($data);
        if ($res){
            $this->success("反馈成功");
        }else{
            $this->error("反馈失败");
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param $file
     * @path api/user/upload
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'full_url' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if(isset($attachment['error_code']) && $attachment['error_code'] == 201){
                $this->error($attachment['msg']);
            }
            if($attachment->imagetype != 'mp4'){
                $image = \think\Image::open('.'.$attachment->url);
                // 给原图左上角添加水印并保存water_image.png
                $image->water('./water.png',\think\Image::WATER_SOUTHEAST)->save('.'.$attachment->url);
            }
            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'full_url' => cdnurl($attachment->url, true)]);
        }
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     * @path api/user/logout
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 注销账号
     * @ApiMethod (POST)
     * @path api/user/cancelAccount
     */
    public function cancelAccount()
    {
        $user = $this->auth->getUser();
        $user->logout = 1;
        $user->add_log_time = time();
        $user->save();
        $this->success("注销成功,请等待审核");
    }

    /**
     * 版本信息
     * @ApiMethod (POST)
     * @path api/user/getVersionInfo
     */
    public function getVersionInfo()
    {
        $duan = $this->request->post("duan");
        if(!$duan){
            $this->error("来源不能为空");
        }
        Db::name("test")->where("id",1)->update(["user_id"=>$duan]);
        $where = "duan = '{$duan}'";
        $field = "id,oldversion,newversion,packagesize,content,downloadurl,enforce,status,duan";
        $info = Db::name("version")->where($where)->field($field)->order("id","desc")->find();
        if(!$info){
            $this->error("版本信息错误");
        }
        if($info['status'] == '3'){
            $edition_issue = 1;
        }else{
            $edition_issue = 0;
        }
        $new_info = [];
        $new_info["version_name"] = $info["oldversion"];
        $new_info["describe"] = $info["content"];
        $new_info["edition_url"] = $info["downloadurl"];
        $new_info["edition_force"] = $info["enforce"];
        $new_info["package_type"] = 0;
        $new_info["edition_issue"] = $edition_issue;
        $new_info["edition_number"] = $info["newversion"];
        $new_info["edition_name"] = $info["newversion"];
        $new_info["edition_silence"] = 0;
        $this->success("请求成功",$new_info);
    }

    /**
     * 用户列表
     * @ApiMethod (POST)
     * @path api/user/getUserList
     */
    public function getUserList()
    {
        $params = $this->request->param();
        $group_type = $this->request->param("group_type",1);
        $user_id = $this->auth->user_id;
        $list = UserModel::getUserList($params,$user_id,$group_type);
        $this->success("请求成功",$list);
    }

    /**
     * 用户分享
     * @ApiMethod (POST)
     * @path api/user/userShare
     */
    public function userShare()
    {
        $share_user_id = $this->request->param("share_user_id");
        $share_type = $this->request->param("share_type");
        $duan = $this->request->post("duan");
        $version = $this->request->post("version");
        // if(($duan == 2 || $duan == 3) && $version == 114){
        //     $data = [
        //         'unlock_times' => 0,
        //         'count' => 0,
        //         'is_share' => 1,
        //     ];
        //     $this->success("请求成功",$data);
        // }
        if(!$share_user_id){
            $data = [
                'unlock_times' => 0,
                'count' => 0,
                'is_share' => 1,
            ];
            $this->success("请求成功",$data);
        }
        if(!$share_type){
            $this->error("类型不能为空");
        }
        // 当天开始时间戳
        $todayStartTimestamp = strtotime("today");
        // 当天结束时间戳
        $todayEndTimestamp = strtotime("tomorrow") - 1;
        $user_id = $this->auth->user_id;
        $where = "user_id = {$user_id} AND add_time >= '{$todayStartTimestamp}' AND add_time <= '{$todayEndTimestamp}'";
        $unlock_times = Db::name("config")->where("name","unlock_times")->value("value",0);
        // 分享
        if($share_type == 1){
            // 查询用户当天是否分享过改用户
            $exists = Db::name("share")->where($where)->where('share_user_id',$share_user_id)
                    ->distinct('share_user_id') // 确保只查找 share_user_id 不重复
                    ->count('share_user_id') > 0; // 判断是否存在
            if(!$exists){
                $share_data = [];
                $share_data['user_id'] = $user_id;
                $share_data['share_user_id'] = $share_user_id;
                $share_data['add_time'] = time();
                Db::name("share")->insert($share_data);
            }
            // 查询 share_user_id 不重复的分享次数
            $count = Db::name("share")->where('user_id', $user_id)
                ->where('add_time', '>=', $todayStartTimestamp)
                ->where('add_time', '<=', $todayEndTimestamp)
                ->distinct('share_user_id') // 确保 share_user_id 不重复
                ->count('share_user_id'); // 统计不重复的分享次数
            if($count > $unlock_times){
                $this->success("解锁已达上线");
            }else{
                $this->success("分享成功");
            }
        }else{
            // 查询 share_user_id 不重复的分享次数
            $count = Db::name("share")->where('user_id', $user_id)
                ->where('add_time', '>=', $todayStartTimestamp)
                ->where('add_time', '<=', $todayEndTimestamp)
                ->distinct('share_user_id') // 确保 share_user_id 不重复
                ->count('share_user_id'); // 统计不重复的分享次数
            $share_user_id_arr = Db::name("share")->where('user_id', $user_id)
                ->where('add_time', '>=', $todayStartTimestamp)
                ->where('add_time', '<=', $todayEndTimestamp)
                ->distinct('share_user_id') // 确保 share_user_id 不重复
                ->order("add_time","asc")
                ->limit($unlock_times)
                ->column('share_user_id');
            $user_info = UserModel::where("user_id",$user_id)->field("authen,end_time")->find();
            if($user_info["authen"] == 3 && strtotime($user_info['end_time']) > time()){
                $is_share = 1;
            }elseif ($count > $unlock_times && in_array($share_user_id,$share_user_id_arr)){
                $is_share = 1;
            }elseif ($count > $unlock_times){
                $is_share = 0;
            }else{
                $is_share = Db::name("share")->where($where)->where('share_user_id',$share_user_id)->count();
            }
            $data = [
                'unlock_times' => $unlock_times,
                'count' => $count,
                'is_share' => $is_share,
            ];
            $this->success("请求成功",$data);
        }
    }


    /**
     * 修改手机号
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

}
